<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>口算练习</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #6B73FF;
            --primary-dark: #000DFF;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --bg-gradient: linear-gradient(135deg, rgba(107, 115, 255, 0.1) 0%, rgba(0, 13, 255, 0.1) 100%);
        }
        
        body {
            background: var(--bg-gradient);
            min-height: 100vh;
            padding: 20px;
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
        }
        
        .container {
            max-width: 1000px;
            background: white;
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .page-title {
            color: var(--primary-color);
            font-weight: 700;
            font-size: 2.5rem;
            margin-bottom: 1.5rem;
            text-align: center;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .grade-select {
            margin-bottom: 30px;
            position: relative;
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
            padding: 20px;
        }
        
        .form-label {
            font-weight: 600;
            color: #444;
            margin-bottom: 10px;
        }
        
        .form-select {
            border: 2px solid rgba(107, 115, 255, 0.2);
            border-radius: 12px;
            padding: 12px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background-color: white;
        }
        
        .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(107, 115, 255, 0.15);
        }
        
        .questions-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 25px;
            margin-bottom: 30px;
            animation: fadeInUp 0.5s ease;
        }
        
        .question-card {
            background: white;
            padding: 20px;
            border-radius: 15px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(107, 115, 255, 0.1);
        }
        
        .question-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(107, 115, 255, 0.15);
            border-color: var(--primary-color);
        }
        
        .question-number {
            font-weight: 700;
            color: var(--primary-color);
            min-width: 45px;
            font-size: 0.9rem;
            padding: 5px 10px;
            background: rgba(107, 115, 255, 0.1);
            border-radius: 8px;
        }
        
        .expression {
            font-size: 1.3em;
            flex-grow: 1;
            text-align: right;
            margin-right: 15px;
            font-weight: 500;
            color: #333;
        }
        
        .answer-input {
            width: 90px;
            text-align: center;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 8px 12px;
            font-size: 1.2em;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }
        
        .answer-input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(107, 115, 255, 0.15);
            outline: none;
            background: white;
        }
        
        .feedback-icon {
            min-width: 30px;
            font-size: 1.2em;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .btn {
            padding: 12px 30px;
            font-weight: 600;
            border-radius: 15px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            font-size: 1.1rem;
            letter-spacing: 0.5px;
        }
        
        .btn-start {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            border: none;
            color: white;
            box-shadow: 0 4px 15px rgba(107, 115, 255, 0.3);
        }
        
        .btn-start:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(107, 115, 255, 0.4);
            color: white;
        }
        
        .btn-submit {
            background: var(--success-color);
            border: none;
            color: white;
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
        }
        
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
            color: white;
        }
        
        .result {
            font-size: 1.5em;
            text-align: center;
            margin: 30px 0;
            padding: 30px;
            border-radius: 20px;
            display: none;
            animation: fadeIn 0.5s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        .result.success {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            color: #155724;
        }
        
        .result.warning {
            background: linear-gradient(135deg, #fff3cd 0%, #ffeeba 100%);
            color: #856404;
        }
        
        .result.danger {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
            color: #721c24;
        }
        
        .emoji {
            font-size: 3em;
            margin: 15px;
            animation: bounce 0.6s ease;
        }
        
        .loading-container {
            text-align: center;
            margin: 30px 0;
            padding: 30px;
            background: white;
            border-radius: 20px;
            display: none;
            animation: fadeIn 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
        }
        
        .loading-spinner {
            display: inline-block;
            width: 3rem;
            height: 3rem;
            border: 0.3rem solid var(--primary-color);
            border-right-color: transparent;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        .loading-text {
            margin-top: 15px;
            color: #666;
            font-size: 1.1em;
            font-weight: 500;
        }
        
        .generating-text {
            font-style: italic;
            color: var(--primary-color);
            margin-top: 10px;
            font-size: 0.9em;
        }
        
        .correct {
            color: var(--success-color);
            animation: fadeIn 0.3s ease;
        }
        
        .incorrect {
            color: var(--danger-color);
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes bounce {
            0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
            40% { transform: translateY(-20px); }
            60% { transform: translateY(-10px); }
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .questions-grid {
                grid-template-columns: 1fr;
            }
            
            .container {
                padding: 20px;
            }
            
            .page-title {
                font-size: 2rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="page-title">趣味口算练习</h1>
        
        <!-- 年级选择 -->
        <div class="grade-select">
            <label class="form-label">选择年级：</label>
            <select id="gradeSelect" class="form-select">
                <option value="1">一年级</option>
                <option value="2">二年级</option>
                <option value="3">三年级</option>
                <option value="4">四年级</option>
                <option value="5">五年级</option>
                <option value="6">六年级</option>
            </select>
        </div>
        
        <!-- 开始按钮 -->
        <div class="text-center mb-4">
            <button id="startBtn" class="btn btn-start">
                <i class="fas fa-play me-2"></i>开始练习
            </button>
        </div>
        
        <!-- 加载提示 -->
        <div id="loadingContainer" class="loading-container">
            <div class="loading-spinner"></div>
            <div class="loading-text">AI正在出题中...</div>
            <div id="generatingText" class="generating-text"></div>
        </div>
        
        <!-- 题目列表 -->
        <div id="questionList" style="display: none;">
            <div id="questions"></div>
            
            <!-- 提交按钮 -->
            <div class="text-center mt-4">
                <button id="submitBtn" class="btn btn-submit">
                    <i class="fas fa-check me-2"></i>提交答案
                </button>
            </div>
        </div>
        
        <!-- 结果显示 -->
        <div id="result" class="result"></div>
    </div>

    <script>
        let currentQuestions = [];
        let isGenerating = false;
        
        document.getElementById('startBtn').addEventListener('click', startPractice);
        document.getElementById('submitBtn').addEventListener('click', submitAnswers);
        
        async function startPractice() {
            if (isGenerating) return;
            
            const startBtn = document.getElementById('startBtn');
            const loadingContainer = document.getElementById('loadingContainer');
            const questionList = document.getElementById('questionList');
            const result = document.getElementById('result');
            const generatingText = document.getElementById('generatingText');
            
            // 重置状态
            currentQuestions = [];
            isGenerating = true;
            startBtn.classList.add('btn-disabled');
            loadingContainer.style.display = 'block';
            questionList.style.display = 'none';
            result.style.display = 'none';
            generatingText.textContent = '';
            
            const grade = document.getElementById('gradeSelect').value;
            const gradeName = ['一', '二', '三', '四', '五', '六'][parseInt(grade) - 1];
            
            try {
                const response = await fetch('/api/ai/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        messages: [{
                            role: 'user',
                            content: `请生成10道${gradeName}年级数学口算题，难度要符合年级水平。请严格按照以下JSON格式返回，不要包含任何其他文字：
{
    "questions": [
        {"expression": "题目表达式", "answer": 答案},
        ...
    ]
}
注意：
1. expression中的运算符：加号用+，减号用-，乘号用×，除号用÷
2. answer必须是数字，不要带单位
3. 如果是分数，请转换为小数
4. 答案最多保留1位小数
5. 请直接返回JSON，不要加任何markdown标记`
                        }],
                        stream: true
                    })
                });
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let accumulatedData = '';
                
                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;
                    
                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            if (data === '[DONE]') continue;
                            
                            try {
                                const parsed = JSON.parse(data);
                                if (parsed.content) {
                                    accumulatedData += parsed.content;
                                    // 尝试从累积的数据中提取题目数量
                                    const questionCount = (accumulatedData.match(/"expression"/g) || []).length;
                                    if (questionCount > 0) {
                                        generatingText.textContent = `正在生成第 ${questionCount} 道题...`;
                                    }
                                }
                            } catch (e) {
                                console.error('解析数据流错误:', e);
                            }
                        }
                    }
                }
                
                try {
                    // 尝试清理并解析JSON数据
                    let jsonStr = accumulatedData;
                    
                    // 如果数据包含markdown代码块，提取JSON部分
                    const jsonMatch = jsonStr.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
                    if (jsonMatch) {
                        jsonStr = jsonMatch[1];
                    }
                    
                    // 清理可能的额外空白和换行
                    jsonStr = jsonStr.trim();
                    
                    // 解析JSON
                    const questionsData = JSON.parse(jsonStr);
                    
                    if (!questionsData.questions || !Array.isArray(questionsData.questions)) {
                        throw new Error('题目数据格式不正确');
                    }
                    
                    currentQuestions = questionsData.questions;
                    
                    // 显示题目
                    const questionsHtml = `
                        <div class="questions-grid">
                            ${currentQuestions.map((q, index) => `
                                <div class="question-card">
                                    <span class="question-number">第${index + 1}题</span>
                                    <span class="expression">${q.expression} =</span>
                                    <input type="number" step="0.1" class="answer-input" id="answer${index}">
                                    <span id="feedback${index}" class="feedback-icon"></span>
                                </div>
                            `).join('')}
                        </div>
                    `;
                    
                    document.getElementById('questions').innerHTML = questionsHtml;
                    questionList.style.display = 'block';
                    
                } catch (parseError) {
                    console.error('解析题目失败:', parseError, '原始数据:', accumulatedData);
                    alert('生成题目失败，请重试');
                }
                
            } catch (error) {
                console.error('Error:', error);
                alert('获取题目失败，请重试');
            } finally {
                isGenerating = false;
                startBtn.classList.remove('btn-disabled');
                loadingContainer.style.display = 'none';
            }
        }
        
        function getFeedback(score) {
            if (score === 100) {
                return {
                    emoji: '🌟',
                    message: '太棒了！满分！'
                };
            } else if (score >= 80) {
                return {
                    emoji: '😊',
                    message: '做得很好！'
                };
            } else if (score >= 60) {
                return {
                    emoji: '🙂',
                    message: '及格了，继续加油！'
                };
            } else {
                return {
                    emoji: '😔',
                    message: '要多加练习哦！'
                };
            }
        }
        
        function submitAnswers() {
            const answers = [];
            const correctAnswers = [];
            
            currentQuestions.forEach((q, index) => {
                const answer = document.getElementById(`answer${index}`).value;
                answers.push(parseFloat(answer) || 0); // 如果输入为空或非数字，使用0
                correctAnswers.push(parseFloat(q.answer));
            });
            
            // 计算得分
            let correctCount = 0;
            const total = answers.length;
            
            answers.forEach((answer, index) => {
                if (Math.abs(answer - correctAnswers[index]) < 0.01) {
                    correctCount++;
                }
            });
            
            const score = Math.round((correctCount / total) * 100);
            const feedback = getFeedback(score);
            
            // 显示结果
            const resultDiv = document.getElementById('result');
            resultDiv.style.display = 'block';
            
            let resultClass = '';
            if (score === 100) resultClass = 'success';
            else if (score >= 60) resultClass = 'warning';
            else resultClass = 'danger';
            
            resultDiv.className = `result ${resultClass}`;
            resultDiv.innerHTML = `
                <div class="emoji">${feedback.emoji}</div>
                <div class="message">${feedback.message}</div>
                <div class="score">得分：${score}分</div>
                <div class="detail">答对${correctCount}题，共${total}题</div>
            `;
            
            // 显示每题的正确性
            currentQuestions.forEach((q, index) => {
                const feedback = document.getElementById(`feedback${index}`);
                const userAnswer = answers[index];
                const correctAnswer = correctAnswers[index];
                
                if (Math.abs(userAnswer - correctAnswer) < 0.01) {
                    feedback.innerHTML = ' ✓';
                    feedback.className = 'correct';
                } else {
                    feedback.innerHTML = ` ✗ (正确答案: ${correctAnswer})`;
                    feedback.className = 'incorrect';
                }
            });
            
            // 滚动到结果区域
            resultDiv.scrollIntoView({ behavior: 'smooth' });
        }
    </script>
</body>
</html> 